package com.itobase.questionnaire.controller;

import com.alibaba.fastjson.JSONObject;
import com.itobase.questionnaire.config.MyProps;
import com.itobase.questionnaire.model.EnumList.States;
import com.itobase.questionnaire.model.ShortUrl;
import com.itobase.questionnaire.model.Survey;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.SectionRateRepository;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.repository.UrlRepository;
import com.itobase.questionnaire.service.impl.SurveyService;
import com.itobase.questionnaire.util.AuthUtil;
import com.itobase.questionnaire.util.DateUtil;
import com.itobase.questionnaire.util.Message;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;


/**
 * @author liucong
 * @date 2018/7/24
 */
@Controller
public class LoginController {

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    SurveyService surveyService;

    @Autowired
    SectionRateRepository sectionRateRepository;

    @Autowired
    UrlRepository urlRepository;

    @Autowired
    MyProps myProps;


    @RequestMapping(value = "signin", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "home", method = RequestMethod.GET)
    public String home() {
        return "home";
    }




    @RequestMapping("q/{shortUrl}")
    public void parseUrl(@PathVariable String shortUrl,
                         HttpServletResponse response) throws IOException {
        final String url = "http://" + myProps.getIp() + ":80/"; // 结尾必需带 /
        final String clientUrl =url.concat("h5/text/from.html?surveyId=");
        ShortUrl shortUrl1 = urlRepository.findByShortUrl(shortUrl);
        if(shortUrl1==null||shortUrl1.getLongUrl()==null){
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("<h4>调查已不存在，无须填写</h4>");
        }else{
            String longUrl = clientUrl+shortUrl1.getLongUrl();
            response.sendRedirect(longUrl);
        }

    }

    /**
     * 手机访问调查controller
     * @param
     * @return
     * @throws Throwable
     */
    /*@GetMapping("client")
    @ResponseBody
    public Message getClientSurvey(@RequestParam String surveyId) throws Throwable {

        Survey survey = surveyRepository.findOne(surveyId);
        if(survey==null){
            return Message.createErr("调查id错误");
        }
        Date now = new Date();
        Date startTime = DateUtil.parse_day(survey.getStartTime());
        Date endTime = DateUtil.parse_day(survey.getEndTime());
        //        if (survey.getState().equals(States.running)) {
        if(now.getTime()>=startTime.getTime()&&now.getTime()<=endTime.getTime()){
            survey.setState(States.running);
            if (survey.getPrivately()) {
                String userId;
                *//*
                任何需要实名填写的调查都先退出匿名账户的登录
                 *//*
                if(SecurityUtils.getSubject().getPrincipal()!=null&&AuthUtil.getUsername().equals("anonymous")){
                    SecurityUtils.getSubject().logout();
                }

                if(SecurityUtils.getSubject().getPrincipal()!=null){
                    userId= AuthUtil.getUserId();
                }else{
                    JSONObject object = new JSONObject();
                    object.put("surveyId",surveyId);
                    return new Message(0,"请先登录",object);
                }
                List<User> userList = survey.getUserList();
                boolean include = false;
                for (User user : userList) {
                    if (user.getId().equals(userId)) {
                        include = true;
                    }
                }
                if (!include) {
                    return Message.createErr("您不属于此次调查的填写人员列表");
                }
            } else {
                AuthUtil.anonymousLogin();
            }
            return Message.createSuc(surveyService.getClientSurvey(survey));
        } else {
            return Message.createErr("该调查不在运行周期内,调查的填写时间段为"+survey.getStartTime()+"至"+survey.getEndTime());
        }
    }*/




    @PostMapping(value = "login")
    @ResponseBody
    public Message Login(@RequestBody User user,HttpServletRequest request) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            long sessionInvalidTimeMilli = 10800 * 1000L;//session有效时间
            subject.getSession().setTimeout(sessionInvalidTimeMilli);
            return Message.createSuc("登录成功");
        } catch (Exception e) {
            return Message.createErr("用户名或密码错误");//返回登录页面
        }
    }


    @RequestMapping(value = "logout",method = RequestMethod.GET)
    @ResponseBody
    public Message logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Message.createSuc("登出成功");
    }
}
